package com.slmxz.tms.core.service;

import com.slmxz.tms.common.component.RedisUserService;
import com.slmxz.tms.common.constant.SystemConstants;
import com.slmxz.tms.system.model.vo.UserInfoVO;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

/**
 * @Author：albert
 * @Date：2025/7/13 22:14
 */
public interface DataScopeService<T> {

    default void dataScopeHandler(T t) throws Exception {
        UserInfoVO user = RedisUserService.currentUser();
        if(t == null || user == null){
            return;
        }
        Class<?> classlz = t.getClass();
        Field[] fields = classlz.getDeclaredFields();
        Field dataOperateField = null;
        Field scopeNoField = null;
        for (Field field : fields) {
            if(field.getName().equals("dataOperate")){
                dataOperateField = classlz.getDeclaredField("dataOperate");
                continue;
            }
            if(field.getName().equals("scopeNo")){
                scopeNoField = classlz.getSuperclass().getDeclaredField("scopeNo");
            }
        }
        if(dataOperateField == null){
            try{
                dataOperateField = classlz.getSuperclass().getDeclaredField("dataOperate");
            }catch (Exception e){
                dataOperateField = classlz.getSuperclass().getSuperclass().getDeclaredField("dataOperate");
            }
        }
        dataOperateField.setAccessible(true);

        if(scopeNoField == null){
            try{
                scopeNoField = classlz.getSuperclass().getDeclaredField("scopeNo");
            }catch (Exception e){
                scopeNoField = classlz.getSuperclass().getSuperclass().getDeclaredField("scopeNo");
            }
        }
        scopeNoField.setAccessible(true);

        if(SystemConstants.CHAR_Y.equals(user.getAllScopeFlag())){
            dataOperateField.set(t,SystemConstants.OPERATE_LIKE); //全部数据权限
            scopeNoField.set(t,"'" + user.getScopeNo() + "%'");
            return;
        }
        scopeNoField.set(t,user.getScopeNo());
        dataOperateField.set(t,SystemConstants.OPERATE_EQUALS);//当前公司权限
    }
}
